package com.example.common.database

import android.content.Context
import android.util.Log
import androidx.room.Room
import com.example.common.database.dao.UserDao

object DBDataSource {

    private const val TAG = "DBDataSource"

    private var mDataBase: AppDataBase? = null
    private var mCurrentDbId = ""

    /**
     * 打开指定用户的数据库
     * @param dbId 可以使用用户id 或 其他能够区分用户身份的id
     *              如果没有区分数据库的需求 那就在Application中初始化
     */
    fun openDB(context: Context, dbId: String) {
        if (mCurrentDbId != "") {
            if (mCurrentDbId != dbId) {
                closeDB()
            } else {
                Log.d(TAG, "dbId:$dbId, has opened db.")
            }
        }
        mCurrentDbId = dbId
        mDataBase =
            Room.databaseBuilder(context, AppDataBase::class.java, "user_${dbId}_db")
                .build()
        Log.d(TAG, "数据库开启成功 openDb:$dbId")

    }

    fun closeDB() {
        mDataBase?.close()
    }

    internal fun getUserDao(): UserDao? {
        return mDataBase?.userDao()
    }
}